<?php
/**
 * S3云存储插件 - 管理界面
 * 
 * @package CommonCloudStorage
 * @author xiaogg
 * @version 1.0
 */

require '../../../zb_system/function/c_system_base.php';
require '../../../zb_system/function/c_system_admin.php';

$zbp->Load();

// 权限检查
if (!$zbp->CheckRights('root')) {
    $zbp->ShowError(6);
    die();
}

// 处理表单提交
if (GetVars('act', 'GET') == 'save') {
    $config = array(
        'enable_sync' => (bool)GetVars('enable_sync', 'POST'),
        'storage_type' => GetVars('storage_type', 'POST'),
        'access_key' => GetVars('access_key', 'POST'),
        'secret_key' => GetVars('secret_key', 'POST'),
        'bucket_name' => GetVars('bucket_name', 'POST'),
        'bucket_domain' => GetVars('bucket_domain', 'POST'),
        'custom_domain' => GetVars('custom_domain', 'POST'),
        'region' => GetVars('region', 'POST'),
        'endpoint' => GetVars('endpoint', 'POST'),
        'directory' => GetVars('directory', 'POST')
    );
    
    CommonCloudStorage_SaveConfig($config);
    
    $zbp->SetHint('good', '配置保存成功！');
    Redirect('./main.php');
}

// 测试连接
if (GetVars('act', 'GET') == 'test') {
    $config = CommonCloudStorage_GetConfig();
    $result = CommonCloudStorage_TestConnection($config);
    
    if ($result['success']) {
        $zbp->SetHint('good', '连接测试成功：' . $result['message']);
    } else {
        $zbp->SetHint('bad', '连接测试失败：' . $result['message']);
    }
    
    Redirect('./main.php');
}

// 批量替换附件地址
if (GetVars('act', 'GET') == 'replace') {
    $replace_type = GetVars('replace_type', 'POST');
    $result = CommonCloudStorage_BatchReplaceUrls($replace_type);
    
    if ($result['success']) {
        $zbp->SetHint('good', '批量替换成功，共处理 ' . $result['count'] . ' 条记录');
    } else {
        $zbp->SetHint('bad', '批量替换失败：' . $result['message']);
    }
    
    Redirect('./main.php');
}

$config = CommonCloudStorage_GetConfig();

// 页面标题
$blogtitle = 'S3云存储插件管理';

require $zbp->path . 'zb_system/admin/admin_header.php';
require $zbp->path . 'zb_system/admin/admin_top.php';
?>

<div id="divMain">
    <div class="divHeader"><?php echo $blogtitle; ?></div>
    <div class="SubMenu">
        <a href="#config"><span class="m-left">基本配置</span></a>
        <a href="#test"><span class="m-left">连接测试</span></a>
        <a href="#batch"><span class="m-left">批量操作</span></a>
    </div>

    <div id="divMain2">
        <!-- 基本配置 -->
        <div id="config">
            <form method="post" action="?act=save">
                <table class="tableBorder" style="width:100%;">
                    <tr>
                        <th colspan="2" style="text-align:center;">基本配置</th>
                    </tr>
                    <tr>
                        <td width="20%"><b>开启同步：</b></td>
                        <td>
                            <input type="checkbox" name="enable_sync" value="1" <?php echo $config['enable_sync'] ? 'checked' : ''; ?> />
                            <span class="note">勾选后将直接上传文件到云存储，不在本地保存</span>
                        </td>
                    </tr>
                    <tr>
                        <td><b>签名固定值：</b></td>
                        <td>
                            <select name="storage_type">
                                <option value="AWS" <?php echo $config['storage_type'] == 'AWS' ? 'selected' : ''; ?>>AWS S3协议</option>
                                <option value="FTP" <?php echo $config['storage_type'] == 'FTP' ? 'selected' : ''; ?>>FTP空间</option>
                            </select>
                            <span class="note">选择存储类型，AWS适用于各大云服务商对象存储</span>
                        </td>
                    </tr>
                    <tr>
                        <td><b>密钥Access Key：</b></td>
                        <td>
                            <input type="text" name="access_key" value="<?php echo htmlspecialchars($config['access_key']); ?>" style="width:300px;" />
                            <span class="note">访问凭证密钥，FTP模式下为用户名</span>
                        </td>
                    </tr>
                    <tr>
                        <td><b>密钥Secret Key：</b></td>
                        <td>
                            <input type="password" name="secret_key" value="<?php echo htmlspecialchars($config['secret_key']); ?>" style="width:300px;" />
                            <span class="note">访问凭证密钥，FTP模式下为密码</span>
                        </td>
                    </tr>
                    <tr>
                        <td><b>存储桶空间名：</b></td>
                        <td>
                            <input type="text" name="bucket_name" value="<?php echo htmlspecialchars($config['bucket_name']); ?>" style="width:300px;" />
                            <span class="note">存储桶名称，FTP模式下为IP地址</span>
                        </td>
                    </tr>
                    <tr>
                        <td><b>存储桶访问域名：</b></td>
                        <td>
                            <input type="text" name="bucket_domain" value="<?php echo htmlspecialchars($config['bucket_domain']); ?>" style="width:300px;" />
                            <span class="note">存储桶默认域名，FTP模式下留空</span>
                        </td>
                    </tr>
                    <tr>
                        <td><b>自定义地址：</b></td>
                        <td>
                            <input type="text" name="custom_domain" value="<?php echo htmlspecialchars($config['custom_domain']); ?>" style="width:300px;" />
                            <span class="note">自定义绑定域名，留空则使用当前网站地址</span>
                        </td>
                    </tr>
                    <tr>
                        <td><b>区域设置：</b></td>
                        <td>
                            <input type="text" name="region" value="<?php echo htmlspecialchars($config['region']); ?>" style="width:300px;" />
                            <span class="note">存储区域，如：us-east-1、ap-beijing等（S3模式必需，FTP模式留空）</span>
                        </td>
                    </tr>
                    <tr>
                        <td><b>自定义端点：</b></td>
                        <td>
                            <input type="text" name="endpoint" value="<?php echo htmlspecialchars($config['endpoint']); ?>" style="width:300px;" />
                            <span class="note">自定义API端点，留空则自动构建（如：https://s3.amazonaws.com）</span>
                        </td>
                    </tr>
                    <tr>
                        <td><b>目录参数：</b></td>
                        <td>
                            <input type="text" name="directory" value="<?php echo htmlspecialchars($config['directory']); ?>" style="width:300px;" />
                            <span class="note">可为空，填写时在返回URL的域名后拼接此目录</span>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" style="text-align:center;">
                            <input type="submit" value="保存配置" class="button" />
                        </td>
                    </tr>
                </table>
            </form>
        </div>

        <!-- 连接测试 -->
        <div id="test" style="margin-top:20px;">
            <table class="tableBorder" style="width:100%;">
                <tr>
                    <th style="text-align:center;">连接测试</th>
                </tr>
                <tr>
                    <td style="text-align:center; padding:20px;">
                        <a href="?act=test" class="button">测试连接</a>
                        <p class="note">点击测试当前配置是否正确</p>
                    </td>
                </tr>
            </table>
        </div>

        <!-- 批量操作 -->
        <div id="batch" style="margin-top:20px;">
            <form method="post" action="?act=replace">
                <table class="tableBorder" style="width:100%;">
                    <tr>
                        <th style="text-align:center;">批量替换附件地址</th>
                    </tr>
                    <tr>
                        <td style="text-align:center; padding:20px;">
                            <select name="replace_type">
                                <option value="to_custom">替换为自定义地址</option>
                                <option value="to_local">替换为本站地址</option>
                            </select>
                            <br><br>
                            <input type="submit" value="开始替换" class="button" onclick="return confirm('确定要批量替换吗？此操作不可逆！');" />
                            <p class="note">批量替换数据库中文章的附件地址</p>
                        </td>
                    </tr>
                </table>
            </form>
        </div>
    </div>
</div>

<?php
require $zbp->path . 'zb_system/admin/admin_footer.php';

/**
 * 测试连接函数
 */
function CommonCloudStorage_TestConnection($config) {
    if ($config['storage_type'] === 'FTP') {
        return CommonCloudStorage_FTP_Test($config);
    } else {
        return CommonCloudStorage_S3_Test($config);
    }
}

/**
 * 批量替换URL函数
 */
function CommonCloudStorage_BatchReplaceUrls($replace_type) {
    global $zbp;
    
    $config = CommonCloudStorage_GetConfig();
    $count = 0;
    
    try {
        // 获取所有文章
        $articles = $zbp->GetArticleList('*', '', '', '', '', '');
        
        foreach ($articles as $article) {
            $content = $article->Content;
            $intro = $article->Intro;
            $updated = false;
            
            if ($replace_type === 'to_custom') {
                // 替换为自定义地址
                $domain = $config['custom_domain'] ?: $zbp->host;
                $pattern = '/(' . preg_quote($zbp->host, '/') . ')([^"\'>\s]+\.(jpg|jpeg|png|gif|webp|bmp))/i';
                $replacement = $domain . '$2';
            } else {
                // 替换为本站地址
                $custom_domain = $config['custom_domain'] ?: $config['bucket_domain'];
                if ($custom_domain) {
                    $pattern = '/(' . preg_quote($custom_domain, '/') . ')([^"\'>\s]+\.(jpg|jpeg|png|gif|webp|bmp))/i';
                    $replacement = $zbp->host . '$2';
                } else {
                    continue;
                }
            }
            
            $new_content = preg_replace($pattern, $replacement, $content);
            $new_intro = preg_replace($pattern, $replacement, $intro);
            
            if ($new_content !== $content || $new_intro !== $intro) {
                $article->Content = $new_content;
                $article->Intro = $new_intro;
                $article->Save();
                $count++;
                $updated = true;
            }
        }
        
        return array('success' => true, 'count' => $count);
        
    } catch (Exception $e) {
        return array('success' => false, 'message' => $e->getMessage());
    }
}
?>